import 'package:flutter/cupertino.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyBgPage.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';

class WriteDiary extends StatefulWidget {
  dynamic diary;
  Function() onRefresh;

  WriteDiary({this.diary, required this.onRefresh});

  @override
  State<StatefulWidget> createState() {
    return _WriteDiary();
  }
}

class _WriteDiary extends State<WriteDiary> {
  bool onlyScan = false;
  TextEditingController controller = TextEditingController();

  submit(bool isSubmit) {
    String content = controller.text;
    if (content.trim().isEmpty) {
      return;
    }
    if (content.trim().length > 3000) {
      showToast("日记内容不能超过3000字");
      return;
    }
    var param = {"studentId": Global.studentId, "comment": content, "isSubmitted": isSubmit};
    if (widget.diary != null) {
      param["dairyId"] = widget.diary["dairyId"];
    }
    if (isSubmit) {
      if (room == null) {
        showToast("提交日記需要選擇教室");
        return;
      }
      param["classroomId"] = room["classroomId"];
    }
    HttpGo(context).post("/Dairy/UpdateDairy", param, (data) {
      PageUtil().back(context);
      widget.onRefresh();
    }, (code, error) => showToast(error));
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      if (widget.diary != null) {
        //查看
        controller.text = widget.diary["content"] ?? "";

        if (!widget.diary["isSubmitted"]) {
          //查看未提交的日記
          getRoom();
        }
      } else {
        //新建
        getRoom();
      }
    });
    super.initState();
  }

  List<dynamic> rooms = [];
  dynamic room;

  getRoom() {
    HttpGo(context).get("/Dairy/GetClassrooomList?studentId=${Global.studentId}", {}, (data) {
      rooms = data["classroomList"];
    }, (code, error) => showToast(error));
  }

  chooseRoom() {
    showWheelDialog2(context, "", rooms, "classroomName", (i) {
      room = rooms[i];
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    onlyScan = (widget.diary != null && widget.diary["isSubmitted"]);
    String date = getStrTime(DateTime.now(), DateUtil.YMD);
    return MyBgPage(
        "",
        Container(
            padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
            margin: EdgeInsets.all(16),
            decoration: Global.getWhiteBg(8),
            child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
              Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                LocalImage("diary.png", height: 24, width: 32),
                Text("我的日記", style: TextStyle(fontSize: 15, color: MyColor.Orange, fontWeight: FontWeight.bold))
              ]),
              Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 16)),
              Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                Text("$date　", style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: MyColor.Green)),
                Expanded(
                    child: Visibility(
                        visible: !onlyScan, child: ChooserBox(room == null ? "選擇教室‍" : "${room["classroomName"]}", onTap: chooseRoom)))
              ]),
              Expanded(
                  child: onlyScan
                      ? SingleChildScrollView(
                          padding: EdgeInsets.only(bottom: 16, top: 12),
                          physics: BouncingScrollPhysics(),
                          child: Container(
                              padding: EdgeInsets.all(8),
                              width: double.infinity,
                              decoration: Global.getBg(MyColor.F3, 4),
                              child: Text("${widget.diary["content"]}")))
                      : Container(
                          padding: EdgeInsets.all(8),
                          margin: EdgeInsets.only(bottom: 16, top: 12),
                          decoration: Global.getBg(MyColor.F3, 4),
                          child: NormalInput(maxLines: 0, controller: controller, fontColor: MyColor.C7D))),
              Visibility(
                  visible: !onlyScan,
                  child: Row(children: [
                    Expanded(child: Button("暫存", height: 32, radius: 4, fontSize: 12, bgColor: MyColor.Orange, onTap: () => submit(false))),
                    Container(width: 16),
                    Expanded(child: Button("提交日記", height: 32, radius: 4, fontSize: 12, bgColor: MyColor.Green, onTap: () => submit(true)))
                  ]))
            ])));
  }
}
